import readline from "readline";
import { Instance } from "./instance";

function READ_LINE_NAME() {
  return "readline";
}

function getRd() {
  let rd = Instance.Instance().get<readline.ReadLine>(READ_LINE_NAME());
  if (rd === null) {
    rd = readline.createInterface(process.stdin, process.stdout);
    Instance.Instance().set(READ_LINE_NAME(), rd);
  }
  return rd;
}

/**
 * 阻塞读取一行数据
 * 当没有 readline 实例时创建一个新的
 * @param msg 需要显示信息
 */
export const ysReadline = (msg: string) => {
  const rd = getRd();

  return new Promise<string>((resolve, reject) => {
    rd!.question(msg, (line) => {
      resolve(line);
    });
  });
};

/**
 * 关闭自动创建的 readline 实例
 */
export const ysReadlineClose = () => {
  const rd = Instance.Instance().get<readline.ReadLine>(READ_LINE_NAME());
  if (rd) {
    rd.close();
    Instance.Instance().remove(READ_LINE_NAME());
  }
};
